package com.nd.fastdp.objcode.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nd.fastdp.db.mybatis.mapper.FdpBaseMapper;
import com.nd.fastdp.framework.pojo.constant.DelStatusEnum;
import com.nd.fastdp.framework.pojo.dto.DelParam;
import com.nd.fastdp.framework.pojo.dto.StateParam;
import com.nd.fastdp.objcode.model.dto.ObjCodeListParam;
import com.nd.fastdp.objcode.model.dto.ObjCodeQueryParam;
import com.nd.fastdp.objcode.model.entity.ObjCode;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;

@Repository
public interface ObjCodeMapper extends FdpBaseMapper<ObjCode> {

    String MODULE_CODE = "OBJCODE_CREATE_MANG";

    default List<ObjCode> list(ObjCodeListParam param){

        return selectList(queryWrapper(param));
    }

    default IPage<ObjCode> page(ObjCodeQueryParam param){

        return selectPage(param.getPage(), queryWrapper(param));
    }

    default Integer count(ObjCodeListParam param){
        return selectCount(queryWrapper(param));
    }

    default Integer codeCount(ObjCodeListParam param){
        return ((BigDecimal)(selectObjs(queryWrapper(param).select("COALESCE(sum(total),0) as total")).get(0))).intValue();
    }

    default Integer codeUsedCount(ObjCodeListParam param){
        return ((BigDecimal)(selectObjs(queryWrapper(param).select("COALESCE(sum(used_count),0) as total")).get(0))).intValue();
    }

    default QueryWrapper<ObjCode> queryWrapper(ObjCodeListParam param){

        QueryWrapper queryWrapper = new QueryWrapper<ObjCode>().eq("del", DelStatusEnum.NORMAL.getValue())
                                            .like(StringUtils.isNotEmpty(param.getName()), "name", param.getName())
                                            .eq(null != param.getState(), "state", param.getState())
                                            .orderByDesc("create_time");

        filterDataAuthority(queryWrapper, MODULE_CODE, param.getLoginUser());

        return queryWrapper;
    }

    default void del(DelParam param) {

        ObjCode ObjCode = null;
        for (String id : param.getIds()) {

            ObjCode = new ObjCode();

            ObjCode.setId(id);
            ObjCode.init(param);
            ObjCode.setDel(DelStatusEnum.DEL.getValue());

            updateById(ObjCode);
        }
    }

    default void updateState(StateParam param) {

        ObjCode ObjCode = null;
        for (String id : param.getIds()) {

            ObjCode = new ObjCode();

            ObjCode.setId(id);
            ObjCode.init(param);
            ObjCode.setState(param.getState());

            updateById(ObjCode);
        }
    }

}
